package com.editor.smsmanager;

import com.editor.smsmanager.utils.MyLog;
import com.google.gson.Gson;

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;

public class SpdServer extends WebSocketServer {
    public static String TAG = "SpdServer";

    public interface onReceiveMessage{
        void onMessage(WebSocket conn, String message);
    }

    onReceiveMessage onReceiveMessage = null;

    List<WebSocket> webSocketList = new ArrayList<>();

    public SpdServer(InetSocketAddress inetSocketAddress) {
        super(inetSocketAddress);
    }

    @Override
    public void onOpen(WebSocket conn, ClientHandshake handshake) {
        webSocketList.add(conn);
        MyLog.D(TAG,"onOpen 新的连接");
    }

    @Override
    public void onClose(WebSocket conn, int code, String reason, boolean remote) {
        webSocketList.remove(conn);
        MyLog.D(TAG,"onOpen 链接关闭");
    }

    @Override
    public void onMessage(WebSocket conn, String message) {
        MyLog.D(TAG,"onMessage:"+message);
        if(onReceiveMessage != null) onReceiveMessage.onMessage(conn, message);
    }

    @Override
    public void onError(WebSocket conn, Exception ex) {
        MyLog.E(TAG,"onError:"+ex);
    }

    @Override
    public void onStart() {
        MyLog.D(TAG,"onStart");
    }

    public void sendHello(){
        SpdJson spdJson = new SpdJson("hello");
        sendSpdJson(spdJson);
    }

    public void sendSpdJson(SpdJson spdJson){
        String json = new Gson().toJson(spdJson);

        for(WebSocket webSocket: webSocketList){
            webSocket.send(json);
        }

        MyLog.D(TAG,"sendSpdJson:"+spdJson.type);
    }

    public void setOnReceiveMessage(SpdServer.onReceiveMessage onReceiveMessage) {
        this.onReceiveMessage = onReceiveMessage;
    }
}
